<?php
header("content-type:text/html;charset=utf-8");
//$handle = fopen("a.txt", "a+");
//$re = fwrite($handle, "notify.php被访问\r");


/**
*
* example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
* 
**/
//include "../../public/config/config.php";
include "./lib/add_table.php";

require_once "./lib/WxPay.Api.php";
require_once './lib/WxPay.Notify.php';
require_once "./example/WxPay.Config.php";
require_once './example/log.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class PayNotifyCallBack extends WxPayNotify
{
	public $dataArr = array();
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);

		$config = new WxPayConfig();
		$result = WxPayApi::orderQuery($config, $input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//添加
	function add($link,$tableName,$arr){
		$keys=array_keys($arr);
		$keys=join(",", $keys);
		$values=array_values($arr);
		$values="'".join("','",$values)."'";
		$sql="insert into $tableName ($keys) values ($values)";
		// echo $sql;
		$re=mysqli_query($link,$sql);
		return $sql;
//		if($re>0){
//			return TRUE;	
//		}else{
//			return FALSE;
//		}
	}
	
	
	/**
	*
	* 回包前的回调方法
	* 业务可以继承该方法，打印日志方便定位
	* @param string $xmlData 返回的xml参数
	*
	**/
	public function LogAfterProcess($xmlData)
	{
		Log::DEBUG("call back， return xml:" . $xmlData);
		return;
	}
	
	//重写回调处理函数
	/**
	 * @param WxPayNotifyResults $data 回调解释出的参数
	 * @param WxPayConfigInterface $config
	 * @param string $msg 如果回调处理失败，可以将错误信息输出到该方法
	 * @return true回调出来完成不需要继续回调，false回调处理未完成需要继续回调
	 */
	public function NotifyProcess($objData, $config, $link, &$msg)
	{
		$data = $objData->GetValues();
		$this->dataArr = $data;
		//TODO 1、进行参数校验
		if(!array_key_exists("return_code", $data) 
			||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
			//TODO失败,不是支付成功的通知
			//如果有需要可以做失败时候的一些清理处理，并且做一些监控
			$msg = "异常异常";
			return false;
		}
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}

		//TODO 2、进行签名验证
		try {
			$checkResult = $objData->CheckSign($config);
			if($checkResult == false){
				//签名错误
				Log::ERROR("签名错误...");
				return false;
			}
		} catch(Exception $e) {
			Log::ERROR(json_encode($e));
		}

		//TODO 3、处理业务逻辑
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
//		$h = fopen("b.txt", "a+");
//		fwrite($h, "notify.php===23被访问". json_encode($data)."\r");
//		file_put_contents('b.txt', "notify.php===234被访问". json_encode($data)."\r",FILE_APPEND);
		
		$addObj = new add_table;
		$link = $addObj->conn();
		
		$arr['out_trade_no'] = $data['out_trade_no'];
		$arr['transaction_id'] = $data['transaction_id'];
		$arr['attach'] = $data['attach'];
		$arr['total_fee'] = $data['total_fee'];
		$arr['trade_type'] = $data['trade_type'];
		$arr['openid'] = $data['openid'];
		$arr['time_int'] = time();
//		$re = $this->add($link, "pay_wx_online", $arr);
		$re = $addObj->add($link,"pay_wx_online",$arr);
//		file_put_contents('b.txt', "notify.php===666被访问".$re. json_encode($data)."\r",FILE_APPEND);
		
/*{"appid":"wx958c2cc16f7108b3",
"attach":"test",
"bank_type":"OTHERS",
"cash_fee":"1",
"fee_type":"CNY",
"is_subscribe":"Y",
"mch_id":"1535913711",
"nonce_str":"397tfhvs35fvclvsuj9myl5xs28eu8a9",
"openid":"oMKYF1brS-9e5ihu6SZsF09zM-Dk",
"out_trade_no":"sdkphp20200628100001",
"result_code":"SUCCESS",
"return_code":"SUCCESS",
"sign":"6A6981CD5F3D947CF72AAFEE62165784DBB03812630CA0CA41439B683AF0C5C5",
"time_end":"20200628100009",
"total_fee":"1",
"trade_type":"JSAPI",
"transaction_id":"4200000576202006285513142370"}*/

				
		
		
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		return true;
	}
}

$config = new WxPayConfig();
Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$xml = $notify->Handle($config, false);


//$hand = fopen("a.txt", "a+");
//$re = fwrite($hand, "notify.php---1999被访问\r");

//$link=conn($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd,$cfg_dbname,$cfg_dbchar);


$obj = WxPayNotifyResults::Init($config, $xml);
$re = $notify->NotifyProcess($obj,$config,'');







?>